package com.example.lenovo.downloaddemo.fragment;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.example.lenovo.downloaddemo.R;
import com.example.lenovo.downloaddemo.activity.LoginActivity;
import com.example.lenovo.downloaddemo.activity.ProductInfoActivity;
import com.example.lenovo.downloaddemo.bean.Customer;
import com.example.lenovo.downloaddemo.bean.ReturnBean;
import com.example.lenovo.downloaddemo.http.AppConfig;
import com.example.lenovo.downloaddemo.http.datasource.MDataSource;
import com.example.lenovo.downloaddemo.http.okhttp.utils.AppContext;
import com.example.lenovo.downloaddemo.http.okhttp.utils.Collintion;
import com.example.lenovo.downloaddemo.http.okhttp.utils.CommonUtils;
import com.example.lenovo.downloaddemo.http.okhttp.utils.MD5;
import com.example.lenovo.downloaddemo.http.okhttp.utils.SharedPreUtils;
import com.example.lenovo.downloaddemo.http.okhttp.utils.ToastUtil;
import com.example.lenovo.downloaddemo.sqlite.LoadListCallBack;
import com.example.lenovo.downloaddemo.util.StatusBarUtil;
import com.example.lenovo.downloaddemo.util.TimeUtil;
import com.example.lenovo.downloaddemo.view.TitleBarView;
import com.google.gson.Gson;

import java.util.HashMap;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Request;

public class PersonalFragment extends Fragment implements View.OnClickListener {
    @Bind(R.id.index_titleBar)
    TitleBarView titleBarView;
    @Bind(R.id.phone)
    TextView tv_phone;//账号
    @Bind(R.id.nickname)
    TextView tv_nickname;//昵称
    @Bind(R.id.logout)
    TextView logout;//退出登陆

    @Bind(R.id.zhanghao)
    TextView zhanghao;
    @Bind(R.id.nicheng)
    TextView nicheng;


    public static PersonalFragment instance;
    private Context context;
    private View view;
    private String allString;

    public static PersonalFragment getInstance(){
        if(null==instance){
            instance=new PersonalFragment();
        }
        return instance;
    }

    private Handler mHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what==1){
                String returnMessage= (String) msg.obj;
                Gson gson=new Gson();
                ReturnBean bean=gson.fromJson(returnMessage,ReturnBean.class);
                if(bean.getCode()==200){
                    SharedPreUtils.clearDatas(context);
                    String name= SharedPreUtils.getPreStringInfo(AppContext.getInstance(), "phone");
                    if(name==null||name.equals("")){
                        ToastUtil.makeText(AppContext.getInstance(),"Success!");
                        Intent intent = new Intent(getActivity(),LoginActivity.class);
                        getActivity().startActivity(intent);
                        getActivity().finish();
                    }
                }else{
                    ToastUtil.makeText(AppContext.getInstance(),bean.getMsg());
                }

            }



        }
    };

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context=context;

    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        if (null == view) {
            view = inflater.inflate(R.layout.fragment_index, container, false);
            ButterKnife.bind(this, view);
            initView();
        } else {
            if (null != view.getParent()) {
                ((ViewGroup) view.getParent()).removeAllViews();
            }

        }
        instance = this;
        return view;
    }

    private void initView() {
        StatusBarUtil.setMargin(context,titleBarView);
        titleBarView.setTitle(AppContext.getInstance().getResources().getString(R.string.center));
        titleBarView.showBackButton(false);
        titleBarView.showEditButton(true);
        zhanghao.setText(AppContext.getInstance().getResources().getText(R.string.userid));
        nicheng.setText(AppContext.getInstance().getResources().getText(R.string.nickname));
        String phone= SharedPreUtils.getPreStringInfo(AppContext.getInstance(), "phone");
        String name= SharedPreUtils.getPreStringInfo(AppContext.getInstance(), "nickname");
        logout.setText(AppContext.getInstance().getResources().getText(R.string.logout));
        if(!TextUtils.isEmpty(phone)&&!TextUtils.isEmpty(name)) {
            tv_phone.setText(phone);
            tv_nickname.setText(name);
        }
        initListener();
    }

    private void initListener() {
        logout.setOnClickListener(this);
    }


    private void Logout(String token){

        HashMap<String, String> map = new HashMap<>();
        map.put("model", "user");
        map.put("method", "logout");
        map.put("token", token);
        map.put("time",new TimeUtil().getMoment());
        Collintion collintion=new Collintion();

        allString=collintion.Sort(map)+"ad1af567dc7bfedd5e760fc1f48a59ae";
        String sign= MD5.GetMD5Code(MD5.GetMD5Code(allString));
        Log.e("拼接字符串",allString);
        Log.e("签名===",sign);
        map.put("sign",sign);
        MDataSource<Customer> dataSource = new MDataSource<>(AppContext.getInstance());
        dataSource.postData(map, new LoadListCallBack() {
            @Override
            public void loadList(List list) {

            }

            @Override
            public void systemError(Request request, String errorInfo, Exception e) {
                Log.e("error", "systemError: " + errorInfo);
                e.printStackTrace();
            }

            @Override
            public void retLoad(String code) {

            }

            @Override
            public void loadString(String string) {
                Log.e("退出登陆", "loadString 获取结果 : " + string);

                Message message=Message.obtain();
                message.what=1;
                message.obj=string;
                mHandler.sendMessage(message);





            }
        });

    }

//    @Override
//    public void onDestroy() {
//        super.onDestroy();
//        getActivity().finish();
//    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.logout:
                final String token=SharedPreUtils.getPreStringInfo(getActivity(),"token");
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setTitle(AppContext.getInstance().getResources().getString(R.string.tishi)).setMessage(AppContext.getInstance().getResources().getString(R.string.sure))
                        .setIcon(R.mipmap.ic_launcher)
                        .setPositiveButton(AppContext.getInstance().getResources().getString(R.string.yes), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                if(CommonUtils.isNetOk(AppContext.getInstance())) {
                                    Logout(token);
                                }else {
                                    ToastUtil.makeText(AppContext.getInstance(),"Fail!");
                                }
                            }
                        })
                        .setNegativeButton(AppContext.getInstance().getResources().getString(R.string.fail),null);
                builder.create().show();



                break;
        }
    }
}
